﻿using System;
using System.Collections;
using System.Configuration;
using NHibernate.Expression;
using System.Web;
using System.Web.Security;
using System.Web.UI;

using SimplePMT.Data;

namespace SimplePMT
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string url = "";

            if (Request.QueryString["ReturnUrl"] != null)
            {
                url = Request.QueryString["ReturnUrl"];
            }
            else
            {
                url = "Home.aspx";
            }

            if (Request.Cookies["MemberID"] != null)
            {
                Session.Add("MemberID", Request.Cookies["MemberID"].Value);
                Session.Add("FullName", Request.Cookies["FullName"].Value);

                FormsAuthentication.SetAuthCookie(Request.Cookies["MemberID"].Value, false);

                Response.Redirect(url);
            }
            else if (Request.Form.Count > 0)
            {
                bool storeInCookie = false;
                if (Request.Form["storeInCookie"] != null) {
                    storeInCookie = Request.Form["storeInCookie"].Equals("1");   
                }

                Member[] member = Member.FindAll(Expression.Eq("UserName", Request.Form["username"]), Expression.Eq("Password", Request.Form["password"]));
                if (member.Length > 0)
                {

                    Session["FullName"] = member[0].FirstName + " " + member[0].LastName;
                    Session["MemberID"] = member[0].ID;
                    FormsAuthentication.SetAuthCookie(member[0].ID.ToString(), false);

                    if (storeInCookie)
                    {
                        if (Request.Cookies["MemberID"] != null)
                        {
                            Response.Cookies["MemberID"].Expires = DateTime.Now.AddYears(1);
                        }
                        else
                        {
                            HttpCookie id = new HttpCookie("MemberID", member[0].ID.ToString());
                            HttpCookie name = new HttpCookie("FullName", member[0].FirstName + " " + member[0].LastName);
                            id.Expires = DateTime.Now.AddYears(1);
                            name.Expires = DateTime.Now.AddYears(1);
                            Response.Cookies.Add(id);
                            Response.Cookies.Add(name);
                        }
                    }
                    Response.Redirect(url);
                } 
                else
                {

                    Response.Write("<script>alert('Login Failed');</script>");
                }
            }
        }
    }
}
